package com.cloud.monitor.service;

import com.cloud.common.domain.Result;
import com.cloud.monitor.utils.ServiceMonitorUtils;
import com.cloud.utils.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class IServiceMonitorService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 服务器监控信息查询
     *
     * @return
     */
    public Result getServerInfo() {
        try {
            ServiceMonitorUtils serviceMonitor = new ServiceMonitorUtils();
            serviceMonitor.copyTo();
            return Result.success("查询成功", serviceMonitor);
        } catch (Exception e) {
            return Result.error("查询服务监控数据异常:" + e);
        }
    }

    /**
     * 服务器缓存监控信息查询
     *
     * @return
     */
    public Result getRedisInfo() {
        try {
            Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
            Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
            Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());
            Map<String, Object> result = new HashMap<>(3);
            result.put("info", info);
            result.put("dbSize", dbSize);
            List<Map<String, String>> pieList = new ArrayList<>();
            commandStats.stringPropertyNames().forEach(key -> {
                Map<String, String> data = new HashMap<>(2);
                String property = commandStats.getProperty(key);
                data.put("name", StringUtils.removeStart(key, "cmdstat_"));
                data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
                pieList.add(data);
            });
            result.put("pieList", pieList);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            return Result.error("查询缓存监控数据异常:" + e);
        }
    }

}
